/**
* All Rights Reserved , Copyright (C) 2023 , 青岛鼎信通讯股份有限公司
*
* AppUserSearchRecordsService
* 用户搜索记录
*
* 修改纪录
* 2023-08-25 版本：1.0 wuyuyang 创建。
* @version 版本：1.0
* @author 作者：wuyuyang
* 创建日期：2023-08-25
*/
package com.topscomm.appv2.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.topscomm.appv2.SystemConst;
import com.topscomm.appv2.pojo.AppUserSearchRecordsEntity;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.appv2.service.IAppUserSearchRecordsService;
import com.topscomm.appv2.service.impl.auto.AppUserSearchRecordsServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service(value = "appUserSearchRecordsService")
@Scope(value = "singleton")
public class AppUserSearchRecordsService extends AppUserSearchRecordsServiceAuto implements IAppUserSearchRecordsService {

    /**
     * @Description:    查询搜索记录
     * @Author:         wuyuyang
     * @Return:         java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @exception:
     * @Date:           25/8/2023 上午10:30
     * @Version:        1.0
     **/
    @Override
    public List<AppUserSearchRecordsEntity> querySearchRecord(Map<String, Object> paraMap) {
        String userCode = ConvertUtil.convertToString(paraMap.get("usercode"));
        String recordType = ConvertUtil.convertToString(paraMap.get("type"));
        if (StringUtil.isEmpty(userCode) || StringUtil.isEmpty(recordType)) {
            throw new MessageException("未传入用户工号或搜索记录分类！");
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("recordtype = '{0}' and usercode = '{1}' and  enabled = 1 order by createon desc", recordType, userCode);
        List<AppUserSearchRecordsEntity> list = this.queryByWhere(sql.toString());
//        List<Map<String, Object>> list = this.queryMapByWhere(sql.toString());
        if (list.size() > SystemConst.USER_SEARCH_NUMBER) {
            // 当前查询记录数量大于指定查询记录条数，就截取指定条数
            list = list.subList(0, SystemConst.USER_SEARCH_NUMBER);
        }
        return list;
    }

    /**
     * @Description:    删除指定用户指定分类的搜索记录
     * @Author:         wuyuyang
     * @Return:         java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @exception:
     * @Date:           25/8/2023 上午11:03
     * @Version:        1.0
     **/
    public void deleteByUserAndRecordtype(Map<String, Object> paraMap) {
        String userCode = ConvertUtil.convertToString(paraMap.get("usercode"));
        String recordType = ConvertUtil.convertToString(paraMap.get("type"));
        if (StringUtil.isEmpty(userCode) || StringUtil.isEmpty(recordType)) {
            throw new MessageException("未传入用户工号或搜索记录分类！");
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("recordtype = '{0}' and usercode = '{1}' and enabled = 1", recordType, userCode);
        this.deleteByWhere(sql.toString());
    }


    /**
     * @Description:    记录用户搜索记录
     * @Author:         wuyuyang
     * @Return:         void
     * @exception:
     * @Date:           25/8/2023 上午11:13
     * @Version:        1.0
     **/
    @Transactional(rollbackFor = Exception.class)
    public void insertSearchRecord(Map<String, Object> paraMap) {
        String userCode = ConvertUtil.convertToString(paraMap.get("usercode"));
        String recordType = ConvertUtil.convertToString(paraMap.get("type"));
        String[] array = this.JSONarrayToArray((JSONArray)paraMap.get("value"));
        if (StringUtil.isEmpty(userCode) || StringUtil.isEmpty(recordType)) {
            throw new MessageException("未传入用户工号或搜索记录分类！");
        }
        if (array.length == 0) {
            throw new MessageException("未传入用户搜索记录！");
        }
        if (array.length > 1) {
            // 处理上传多条搜索记录的情况
           this.dealtWithMultipleValues(userCode, recordType, array);
        } else {
            // 处理上传单条搜索记录的情况
            String value = ConvertUtil.convertToString(array[0]).trim();
            if (StringUtil.isEmpty(value)) {
                throw new MessageException("传入搜索记录为空！");
            }
            AppUserSearchRecordsEntity appUserSearchRecordsEntity = new AppUserSearchRecordsEntity();
            // 用户工号
            appUserSearchRecordsEntity.setUsercode(userCode);
            // 搜索记录类别
            appUserSearchRecordsEntity.setRecordtype(recordType);
            // 搜索内容
            appUserSearchRecordsEntity.setValue(value);
            this.insert(appUserSearchRecordsEntity);

            // 删除历史搜索记录中已有相同内容
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle("recordtype = '{0}' and usercode = '{1}'  and  value = '{2}' and enabled = 1", recordType, userCode, value);
            if (this.getCount(sql.toString()) > 1) {
                sql.clear();
                // 删除相同搜索记录时间较早的一条
                sql.appendSingle("delete from appusersearchrecords where enabled = 1 and recordtype = '{0}' and usercode = '{1}'  and  value = '{2}' and createon = ( select min(createon) from appusersearchrecords where enabled = 1 and recordtype = '{0}' and usercode = '{1}'  and  value = '{2}')", recordType, userCode, value);
                this.deleteExecute(sql.toString());
            }
            sql.clear();
            // 删除用户搜索记录多余条数
            sql.appendSingle("recordtype = '{0}' and usercode = '{1}' and enabled = 1", recordType, userCode);
            if (this.getCount(sql.toString()) > SystemConst.USER_SEARCH_NUMBER) {
                sql.clear();
                sql.appendSingle("delete from appusersearchrecords where recordtype = '{0}' and usercode = '{1}' and enabled = 1 and id not in ( SELECT id FROM ( select id from appusersearchrecords where recordtype = '{0}' and usercode = '{1}' and enabled = 1 order by createon desc ) where rownum <= {2} ) ", recordType, userCode, SystemConst.USER_SEARCH_NUMBER);
                this.deleteExecute(sql.toString());
            }
        }
    }

    /**
     * @Description:    处理多条搜索记录情况
     * @Author:         wuyuyang
     * @Return:         void
     * @exception:
     * @Date:           28/8/2023 上午9:41
     * @Version:        1.0
     **/
    @Transactional(rollbackFor = Exception.class)
    public void dealtWithMultipleValues(String userCode, String recordType, String[] array) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("recordtype = '{0}' and usercode = '{1}' and enabled = 1", recordType, userCode);
        List<AppUserSearchRecordsEntity> appUserSearchRecords = this.queryByWhere(sql.toString());
        List<BasicEntity> recordsForRes = new ArrayList<BasicEntity>();
        List<String> resList = new ArrayList<>(Arrays.asList(array));
        // 待删除记录id
        List<String> delIds = new ArrayList<>();
        // 批量删除已有记录
        resList.stream().forEach(m -> {
            String value =  ConvertUtil.convertToString(m).trim();
            if (!StringUtil.isEmpty(value)) {
                appUserSearchRecords.stream().forEach(n -> {
                    if (value.equals(ConvertUtil.convertToString(n.getValue()))) {
                        delIds.add(ConvertUtil.convertToString(n.getId()));
                    }
                });
                AppUserSearchRecordsEntity appUserSearchRecordsEntity = new AppUserSearchRecordsEntity();
                // 用户工号
                appUserSearchRecordsEntity.setUsercode(userCode);
                // 搜索记录类别
                appUserSearchRecordsEntity.setRecordtype(recordType);
                // 搜索内容
                appUserSearchRecordsEntity.setValue(value);
                recordsForRes.add(appUserSearchRecordsEntity);
            }
        });
        if (delIds.size() > 0) {
            this.deleteByIds(delIds.toArray(new String[0]));
        }
        this.insertBatch(recordsForRes);
        sql.clear();
        // 删除用户搜索记录多余条数
        sql.appendSingle("recordtype = '{0}' and usercode = '{1}' and enabled = 1", recordType, userCode);
        if (this.getCount(sql.toString()) > SystemConst.USER_SEARCH_NUMBER) {
            sql.clear();
            sql.appendSingle("delete from appusersearchrecords where recordtype = '{0}' and usercode = '{1}' and enabled = 1 and id not in ( SELECT id FROM ( select id from appusersearchrecords where recordtype = '{0}' and usercode = '{1}' and enabled = 1 order by createon desc ) where rownum <= {2} ) ", recordType, userCode, SystemConst.USER_SEARCH_NUMBER);
            this.deleteExecute(sql.toString());
        }
    }

    /**
     * @Description:    json数组转数组
     * @Author:         wuyuyang
     * @Return:         java.lang.String[]
     * @exception:
     * @Date:           28/8/2023 上午11:42
     * @Version:        1.0
     **/
    public String[] JSONarrayToArray(JSONArray jsonArray){
        String[] res = null;
        try {
            int size = jsonArray.size();
            res = new String[size];
            for (int i = 0; i < size; i++) {
                res[i] = jsonArray.getString(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return res;
    }
}
